#!/usr/bin/env bash
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
# Function :CentOS7.X NFS安装脚本
# Platform :RedHatEL7.x Based Platform
# Version  :1.0
# Date     :2020-08-28
# Author   :mugoLH
# Contact  :hxsaj@126.com
# Company  :
# depend on:
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

#  公共变量列表 List of common variables
########## ########## ########## ########## ########## ########## #
TMP_FILE=.nfs.tmp

# [ ---- ---- 色彩函数定义

#    提示 # echo -e "\033[38;46m 色彩测试-提示 \033[0m"
function show_notice(){ echo -e "\033[34;40m $@ \033[0m" >&1; }
#    警告 # echo -e "\033[35;46m 色彩测试-警告 \033[0m"
function show_warning(){ echo -e "\033[35;46m $@ \033[0m" >&2; }
#    报错 # echo -e "\033[1;31;46m 色彩测试-错误 \033[0m"
function show_error(){ echo -e "\033[1;31;46m $@ \033[0m" >&2; }

#  关闭SELinux
function selinux_off() {
	[ $(grep -w ^SELINUX /etc/selinux/config|awk -F "=" '{print$2}') == "enforcing" ] && sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
	[[ $(getenforce) == "Enforcing" ]] && setenforce 0 >/dev/null 2>&1
}

#  防火墙关闭并禁用
function firewalld_disable(){
	[ $(systemctl list-unit-files|grep firewalld.service|awk '{print$2}') != "disabled" ] && systemctl disable firewalld >/dev/null 2>&1
	[ $(systemctl status firewalld |grep -w Active|awk '{print$2}') == "active" ] && systemctl stop firewalld
}

function yum_install_soft(){
	if [[ $(rpm -aq |grep "${1}" | wc -l) -gt 0 ]];then
		if [ $# -eq 2 ];then
			show_notice " ${2}，已安装 ${1}"
		elif [ $# -eq 1 ]; then
			show_notice " 已安装 ${1}"
		fi
	else
		if [ $# -eq 2 ];then
			yum install ${1} -y   >/dev/null && show_notice " ${2}，${1} 安装完成"
		elif [[ $# -eq 1 ]]; then
			yum install ${1} -y   >/dev/null && show_notice " ${1} 安装完成"
		fi
	fi
}


function nfs_install_yum() {
	#  检查软件是否已安装
	if [ $(rpm -qa |grep nfs-utils|wc -l) -ge 1 ] && [ $(rpm -qa |grep rpcbind|wc -l) -ge 1 ] ;then
		[[ $(systemctl status rpcbind|grep -w "Active"|awk '{print$2}') != "active" ]] && systemctl start rpcbind
		[[ $(systemctl status nfs|grep -w "Active"|awk '{print$2}') != "active" ]]     && systemctl start nfs
		show_notice "NFS已启动！"
	else
		# 第一步：关闭selinux和防火墙阶段
		selinux_off       && show_notice " 1，关闭&禁用 selinux"
		firewalld_disable && show_notice " 2，关闭&禁用 firewalld"
		# 第二步：确认软件是否安装
		yum_install_soft rpcbind 3
		yum_install_soft nfs-utils 4
		# 第三步：启动服务开机自启动
		systemctl restart rpcbind.service nfs.service
		systemctl enable nfs >/dev/null 2>&1
		show_notice " nfs共享服务已搭建完成！"
	fi
}

function nfs_publication_service() {
	# 如果没有启动，则启动
	systemctl start nfs rpcbind

	# 创建和发布共享目录
	if [ $# -eq 0 ];then
		read -p "请输入需要共享的目录：" Exportfs_Dir
		if [[ ! -d ${Exportfs_Dir} ]];then
			mkdir ${Exportfs_Dir} -p >/dev/null && chmod 1777 ${Exportfs_Dir}
			chown -R nfsnobody:nfsnobody ${Exportfs_Dir}
		fi
		read -p "请输入需要共享的网段（如果允许全网访问，请输入*，默认为*）：" Exportfs_Net
		if [ $(echo ${Exportfs_Net} | wc -c) -eq 1 ];then
			Exportfs_Net="*"
		fi
		echo -e "${Exportfs_Dir}  ${Exportfs_Net}(rw,async,all_squash,insecure,async,wdelay)" >>/etc/exports
	elif [ $# -eq 1 ];then
		Exportfs_Dir=${1}
		Exportfs_Net=*
		if [[ ! -d ${Exportfs_Dir} ]];then
			mkdir ${Exportfs_Dir} -p >/dev/null && chmod 1777 ${Exportfs_Dir}
		fi
		echo -e "${Exportfs_Dir}  ${Exportfs_Net}(rw,async,all_squash,insecure,async,wdelay)" >>/etc/exports
	fi
	show_notice "NFS共享状态："
	nfs_server_show
}

function nfs_server_off() {
	# 关闭分发，关闭服务
	if [[ $(showmount -e localhost | grep -v "Export" | wc -l) -gt 0 ]];then
		show_notice " 关闭本服务器全部NFS共享......"
		#exportfs -u $(awk -F "(" '{print$1}' /etc/exports | awk '{print$2":"$1}')
		echo > /etc/exports
	else
		show_notice " 本服务器无NFS共享分发......"
	fi
}

function nfs_server_del_dir() {
	# 已分发共享 NFS 目录和许可网段
	nfs_server_show
	if [ ${EXPORT_STATUS} -ne 0 ];then
		NFS_DIR_NU=$(grep "[0-9])" ${TMP_FILE} |wc -l)
		show_error "[ 删除需谨慎 ]!!!"
		read -p "输入序号：" Choose_Del_Dir_nu
		if echo ${Choose_Del_Dir_nu} |grep -q "^[0-9]" ;then
			if [ ${Choose_Del_Dir_nu} -le ${NFS_DIR_NU} ] && [ ${Choose_Del_Dir_nu} -gt 0 ];then
				Choose_Del_Dir=$(cat ${TMP_FILE} | awk "\$1==\"${Choose_Del_Dir_nu})\" {print\$4}")
				grep -v "${Choose_Del_Dir}" /etc/exports > /etc/.exports
				cat /etc/.exports >/etc/exports
				show_notice "NFS共享状态："
				nfs_server_show
			else
				echo "输入有误，请按序号输入选择操作！"
				nfs_server_del_dir
			fi
		else
			echo "输入有误，请按序号输入选择操作！"
			nfs_server_del_dir
		fi
	fi
}

#  展示当前共享的目录
function nfs_server_show() {
	echo > ${TMP_FILE}
	export EXPORT_STATUS=$(exportfs -rv 2>/dev/null |grep exporting | wc -l )
	if [ ${EXPORT_STATUS} -gt 0 ];then
		exportfs -rv |awk -F " |:" '{print$1,$2,$3}' |awk '$0=NR") "$0' | awk '
		BEGIN{
			print  "  ----------------------------------------------------------";
			printf "  |%-4s| %-8s|  %-12s| %-11s |\n","序号","状态","允许的客户端IP","共享目录" ;
			print  "  ----------------------------------------------------------";
		}
		{
			printf "   %-5s  %-11s %-20s %-1s \n",$1,$2,$3,$4;
		}
		END{
			print  "  ----------------------------------------------------------";
		}' | tee -a ${TMP_FILE}
		
	else
		show_warning " 当前没有 NFS 共享目录！"
		export EXPORT_STATUS=0
	fi
}


if [ $# -eq 1 ];then
	if [[ $(systemctl status rpcbind|grep -w "Active"|awk '{print$2}') != "active" ]] && [[ $(systemctl status nfs|grep -w "Active"|awk '{print$2}') != "active" ]];then
		nfs_install_yum
	fi
	nfs_publication_service ${1}

elif [ $# -eq 0 ];then

	show_notice "\n----------------------- 欢迎使用 NFS 运维脚本！-----------------------\n"
	if [ $(ps -ef | grep nfsd | grep -v grep | wc -l) -gt 0 ];then
		show_notice "  NFS目录共享状态："
		nfs_server_show
	fi
	while true ; do
		# 执行选择NFS相关服务
		echo -e "\n操作选择：
    1，  部署 NFS Server
    2，  新增 分发 共享目录
    3，  关闭 分发 共享目录
    off，关闭 所有 共享目录
    q，  退出
    "
    	read -t 60 -p "请选择（选择序列号即可）：" Choose_Nfs_Service
    	case ${Choose_Nfs_Service} in
    		# 部署NFS Server
    		"1") nfs_install_yum         ;;

    		# 新建分发共享目录
    		"2") nfs_publication_service ;;

    		# 删除分发共享目录
    		"3") nfs_server_del_dir      ;;

    		# NFS Server 关闭分发（不关闭服务进程）
    		"off") nfs_server_off        ;;

    		# 退出程序
    		"q")  exit                   ;;

    		# 输入不规范提示并退出
    		*) echo "输入有误，请输入以上编号选择操作！" ;;

    	esac
	done
fi
